<template>
    <div class="account_manage systemAdminAccount">
        <div class="content_panel_top">
            <h3 class="panel_title">
                <span>{{ $t('system.userManage') }}</span>
            </h3>
            <el-form ref="form" :model="form" :rules="rules" :inline="false" class="module_form">
                <el-row :gutter="20">
                    <el-col :span="4">
                        <el-form-item prop="id">
                            <el-input v-model="form.userName" :placeholder="$t('system.userName')" maxlength="201"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col v-if="isSystemAdmin" :span="4">
                        <el-form-item><!--用户类型-->
                            <el-select class="account_form_type" v-model="form.skillType" :placeholder="$t('system.userType')" clearable>
                                <el-option v-for="skill in skillTypeList" :key="skill.id" :value="skill.id" :label="($i18n.locale === 'zhCN') ? skill.cnName : skill.name"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-form-item><!--角色名-->
                            <el-select class="account_form_type" v-model="form.roleId" :placeholder="$t('system.roleName')" clearable>
                                <el-option v-for="role in roleList" :key="role.id" :value="role.id" :label="role.name"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-form-item prop="status">
                            <el-select v-model="form.status" clearable :placeholder="$t('common.status')" style="width: 100%"><!--状态-->
                                <el-option key="0" :label="$t('collection.closed')" :value="0"></el-option>
                                <el-option key="1" :label="$t('collection.activated')" :value="1"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-form-item>
                            <el-button type="primary" @click="onSearch" icon="search">{{ $t('common.search') }}</el-button>
                        </el-form-item>
                    </el-col>
                    <el-col :span="isSystemAdmin ? 4 : 8" align="right">
                        <el-button @click="editAccount('add')" type="primary">{{ $t('system.addUser') }}</el-button><!--新增用户-->
                    </el-col>
                </el-row>
            </el-form>
        </div>

        <div class="data_list">
            <el-table :data="tableData" :max-height="tableMaxHeight" style="width: 100%">
                <el-table-column align="left" label="ID" prop="id"></el-table-column>
                <el-table-column align="left" :label="$t('system.userName')" prop="username" min-width="180"><!--用户名--></el-table-column>
                <el-table-column align="left" :label="$t('system.roleName')" prop="roleName" min-width="140"><!--角色名--></el-table-column>
                <el-table-column align="left" :label="$t('system.userType')" prop="skillTypeName" min-width="140"><!--用户类型-->
                    <template slot-scope="{ row }">{{ $i18n.locale === 'zhCN' ? row.skillTypeCnName : row.skillTypeName }}</template>
                </el-table-column>
                <el-table-column :label="$t('common.createTime')" prop="createTime" min-width="170"><!--创建时间-->
                    <template slot-scope="{ row }">{{ row.createTime | formatDate('yyyy-MM-dd hh:mm:ss') }}</template>
                </el-table-column>
                <el-table-column :label="$t('common.updateTime')" prop="updateTime" min-width="170"><!--更新时间-->
                    <template slot-scope="{ row }">{{ row.updateTime | formatDate('yyyy-MM-dd hh:mm:ss') }}</template>
                </el-table-column>
                <el-table-column prop="status" :label="$t('common.status')" min-width="100"><!--状态-->
                    <template slot-scope="scope">
                        <el-switch @change="changeStatus(scope.row)" v-model="scope.row.status"></el-switch>
                    </template>
                </el-table-column>
                <el-table-column align="left" :label="$t('system.permission')" min-width="170"><!--权限-->
                    <template slot-scope="scope">
                        <el-button @click="editAccount('edit',scope.row)" :disabled="scope.row.status === false" class="btn" type="text" size="small">{{ $t('system.bindingRole') }}</el-button><!--绑定角色-->
                        <el-button @click="resetPwd(scope.row)" :disabled="scope.row.status === false" class="btn" type="text" size="small">{{ $t('system.resetPassword') }}</el-button><!--重置密码-->
                    </template>
                </el-table-column>
            </el-table><!--end table-->
        </div>
        <div class="data_page">
            <pagination @pageChange="pageChange" :page="page"><!--分页组件--></pagination>
        </div>

        <!--绑定角色start-->
        <el-dialog :title="$t('system.userInformation')" :visible.sync="editDialog.isVisible" width="900px" class="editDialog">
            <el-form class="role_form" ref="roleForm" :model="roleForm" :rules="roleRules" label-position="top">
                <el-form-item :label="$t('system.userName')" prop="userName"><!--用户名-->
                    <el-input v-model="roleForm.userName" type="text" :disabled="editDialog.type === 'edit'" maxlength="100" style="width:40%;display: inline-block"></el-input><span v-if="editDialog.type === 'add'" class="companyName">@{{ domain }}</span>
                </el-form-item>
                <el-form-item :label="$t('system.userType')" prop="userType"><!--用户类型-->
                    <el-select class="account_form_type" v-model="roleForm.userType" :placeholder="$t('system.userType')" clearable  :disabled="editDialog.type === 'edit' || !isSystemAdmin">
                        <el-option v-for="skill in skillTypeList" :key="skill.id" :value="skill.id" :label="($i18n.locale === 'zhCN') ? skill.cnName : skill.name"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item :label="$t('system.userRoleList')" prop="roleIds"><!--用户角色列表-->
                    <div v-if="!roleList || roleList.length <= 0">{{ $t('system.noAvailableRole') }}</div>
                    <el-radio-group v-model="roleForm.roleIds">
                        <el-row>
                            <el-col v-for="role in roleList" v-if="role.status === 1" :key="role.id" :span="8">
                                <el-radio :label="role.id">{{ role.name }}</el-radio>
                            </el-col>
                        </el-row>
                    </el-radio-group>
                </el-form-item>
            </el-form>
            <div slot="footer">
                <el-button @click="editAccountSubmit" type="primary">{{ $t('system.binding') }}</el-button><!--绑定-->
                <el-button @click="editDialog.isVisible = false" type="default">{{ $t('common.cancel') }}</el-button>
            </div>
        </el-dialog>
        <!--绑定角色end-->
    </div>
</template>

<script>
    import Pagination from '@/components/pagination';
    import mixin from '@/service/mixin';
    import AlertDialog from '@/components/alert-dialog';

    export default {
        name: 'systemAccount',
        components: {
            Pagination,
            AlertDialog
        },
        mixins: [mixin],
        data() {
            return {
                isSystemAdmin: null,// 是否主系统管理员
                companyName: '',
                domain: '',
                form: {
                    userName: '',
                    skillType: '',
                    roleId: '',
                    status: 1,
                },
                rules: {},
                //bindRoleDialogShow: false,
                roleForm: {
                    userId: '',
                    userName: '',
                    userType: '',
                    roleIds: []
                },
                roleRules: {
                    userName: [
                        {required: true, message: this.$t('verify.plsInput'), trigger: 'blur'},
                        {pattern: /^[A-Za-z0-9]+$/, message: this.$t('verify.plsInputNumberAlp'), trigger: 'blur'}
                    ],
                    userType: [
                        {required: true, message: this.$t('verify.plsChoose'), trigger: 'change'},
                    ],
                    roleIds: [
                        {required: true, message: this.$t('verify.plsChoose'), trigger: 'change'},
                    ]
                },
                roleList: [],
                addAccountDialogShow: false,
                accountForm: {
                    userName: '',
                    type: ''
                },
                accountRules: {
                    userName: [
                        {required: true, message: this.$t('verify.plsInput'), trigger: 'blur'},
                        {pattern: /^[A-Za-z0-9]+$/, message: this.$t('verify.plsInputNumberAlp'), trigger: 'blur'}
                    ],
                    type: [
                        {required: true, message: this.$t('verify.plsChoose'), trigger: 'blur'}
                    ]
                },
                skillTypeList: [],
                editDialog: {
                    type: '',
                    isVisible: false
                }
            };
        },
        methods: {
            getTableData(page = this.page) {
                const form = this.form;
                const params = {
                    username: this.form.userName,
                    status: form.status,
                    roleId: form.roleId,
                    skillTypeId: form.skillType,
                    pageNum: page.currentPage,
                    pageSize: this.page.pageSize
                };
                this.$api.systemManage.getUserList(params).then((res) => {
                    const {status, data, error} = res;
                    if ('1' === status && error === '00000000') {
                        this.tableData = data.userList || [];
                        this.tableData.forEach((item) => {
                            item.status = +item.status === 1;
                        });
                        this.setPage({total: data.total,page: page.currentPage}, this.page);
                        this.tableMaxHeight = window.document.body.clientHeight - 200;
                    }
                });
            },
            getRoleList(userId) {
                const params = {
                    userId
                };
                this.roleForm.roleIds = [];
                this.$api.systemManage.getRoleList(params).then((res) => {
                    const {status, data, error} = res;
                    if ('1' === status && error === '00000000') {
                        if (userId) {
//                            data.roleList.forEach((item) => {
//                                this.roleForm.roleIds.push(item.id);
//                            });
                            this.roleForm.roleIds = data.roleList && data.roleList[0] ? data.roleList[0].id : ''
                        } else {
                            this.roleList = data.roleList;
                        }
                    }
                });
            },
            onSearch() {
                this.page.currentPage = 1;
//                if (this.form.skillType) {
//                    this.getUserListBySkillType();
//                } else {
//                    this.getTableData();
//                }
                this.getTableData();
            },
            resetPwd(row) {
                this.$confirm(this.$tc('system.isResetPsw', 1, {x: row.username}), '', {
                    confirmButtonText: this.$tc('common.confirm'),
                    cancelButtonText: this.$tc('common.cancel'),
                    type: 'warning'
                }).then(() => {
                    const params = {
                        id: row.id
                    };
                    this.$api.systemManage.resetPassword(params).then((res) => {
                        const {status, error, msg} = res;
                        if ('1' === status && error === '00000000') {
                            this.onSearch();
                            this.$message({
                                message: this.$tc('common.successfulOperation'),
                                type: 'success',
                                showClose: true,
                                duration: 1000,
                            });
                        }
                        else {
                            this.$message({
                                message: msg || this.$tc('common.failedOperation'),
                                type: 'error',
                                showClose: true,
                                duration: 1000,
                            });
                        }
                    });
                }).catch(() => {
                });
            },
            getSkillTypeList() {
                // 获取用户类型
                this.$api.systemManage.getSkillTypeList().then((res) => {
                    const {status, data, error} = res;
                    if ('1' === status && '00000000' === error && data.skillTypeList) {
                        this.skillTypeList = data.skillTypeList;
                    }
                });
            },
            // 状态开关
            changeStatus(row) {
                this.$confirm(row.status === true ? this.$tc('system.isOpenUser') : this.$tc('system.isCloseUserHasOrder'), '', {
                    confirmButtonText: this.$tc('common.confirm'),
                    cancelButtonText: this.$tc('common.cancel'),
                    type: 'warning'
                }).then(() => {
                    this.operStatus(row);
                }).catch(() => {
                    row.status = !row.status;
                });
            },
            // 状态操作
            operStatus(row) {
                const params = {
                    id: row.id
                };
                this.$api.systemManage.deleteUser(params).then((res) => {
                    const { status, error, msg } = res;
                    if ('1' === status && '00000000' === error) {
                        this.onSearch();
                        this.$message({
                            message: this.$tc('common.successfulOperation'),
                            type: 'success',
                            showClose: true,
                            duration: 1000,
                        });
                    }
                    else if('70000113' === error) {
                        this.getTableData();
                        this.$message({
                            message: msg || this.$tc('system.userRoleColse'),
                            type: 'error',
                            showClose: true,
                            duration: 1000,
                        });
                    }
                    else {
                        this.getTableData();
                        this.$message({
                            message: msg || this.$tc('common.failedOperation'),
                            type: 'error',
                            showClose: true,
                            duration: 1000,
                        });
                    }
                });
            },
            editAccount(type,row) {
                this.editDialog.type = type;
                this.editDialog.isVisible = true;
                if(type === 'add') {
                    this.roleForm.userId = '';
                    this.roleForm.userName = '';
                    this.roleForm.userType = '';
                    this.roleForm.roleIds = '';
                    if(!this.isSystemAdmin) {
                        this.roleForm.userType = this.$storage.get('user').skillTypeId;
                    }
                }
                if(type === 'edit') {
                    this.roleForm.userId = row.id;
                    this.roleForm.userName = row.username;
                    this.roleForm.userType = row.skillTypeId;
                    this.roleForm.roleIds = row.roleId;
                }
                this.$nextTick( () => {
                    this.$refs.roleForm.clearValidate();
                });
            },
            editAccountSubmit() {
                const type = this.editDialog.type;
                const form = this.roleForm;
                if(type === 'add') {
                    this.$refs.roleForm.validate((value) => {
                        if (value) {
                            const params = {
                                username: form.userName + '@' + this.domain,
                                skillTypeId: this.isSystemAdmin ? form.userType : this.$storage.get('user').skillTypeId,
                                roleIdList: [form.roleIds]
                            };
                            this.$api.systemManage.addUserRole(params).then((res) => {
                                const {status, error, msg} = res;
                                if ('1' === status && error === '00000000') {
                                    this.editDialog.isVisible = false;
                                    this.$message({
                                        message: this.$tc('common.successfulOperation'),
                                        type: 'success',
                                        showClose: true,
                                        duration: 1000,
                                    });
//                                    if (this.form.skillType) {
//                                        this.getUserListBySkillType();
//                                    } else {
//                                        this.getTableData();
//                                    }
                                    this.onSearch();
                                }
                                else if(error === '70000107') {
                                    this.$message({
                                        message: msg || this.$tc('system.nameIsExist'),
                                        type: 'error',
                                        showClose: true,
                                        duration: 1000,
                                    });
                                }
                                else {
                                    this.$message({
                                        message: msg || this.$tc('common.failedOperation'),
                                        type: 'error',
                                        showClose: true,
                                        duration: 1000,
                                    });
                                }
                            });
                        }
                    });
                }
                if(type === 'edit') {
                    const params = {
                        userId: form.userId,
                        roleIdList: [form.roleIds]
                    };
                    this.$api.systemManage.editUserRole(params).then((res) => {
                        const {status, error, msg} = res;
                        if ('1' === status && error === '00000000') {
                            this.editDialog.isVisible = false;
                            this.$message({
                                message: this.$tc('common.successfulOperation'),
                                type: 'success',
                                showClose: true,
                                duration: 1000,
                            });
//                            if (this.form.skillType) {
//                                this.getUserListBySkillType();
//                            } else {
//                                this.getTableData();
//                            }
                        }
                        else {
                            this.$message({
                                message: msg || this.$tc('common.failedOperation'),
                                type: 'error',
                                showClose: true,
                                duration: 1000,
                            });
                        }
                        this.getTableData();
                    });
                }
            }
        },
        created() {
            const user = this.$storage.get('user');
            this.isSystemAdmin = (user.skillTypeId === 7);
            if(!this.isSystemAdmin) {
                this.form.skillType = user.skillTypeId;
                this.roleForm.userType = user.skillTypeId;
            }
            this.companyName = user.companyName;
            this.domain = user.domain;
            this.onSearch();
            this.getRoleList();
            this.getSkillTypeList();
        }
    };
</script>

<style lang="scss" scoped>
    .inputPhone {
        width: 265px;
    }

    .search {
        background-color: #fff;
        padding: 22px 40px 0;
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
    }

    .data_list {
        background-color: #fff;
        margin: 16px 24px;
        padding: 10px 16px;
    }

    .btn {
        margin-right: 15px;
    }

    .btn_red {
        /*border-color: #d9415c;*/
        color: #d9415c;
    }

    // .role_form {
    /*padding: 0 16px;*/
    // }

    .account_form_type {
        width: 100%;
    }
    .editDialog {
        .companyName {
            word-wrap:break-word;
            display: inline-block;
            vertical-align: middle;
            width: 58%;
            overflow: hidden;
            text-overflow:ellipsis;
            white-space: nowrap;
            padding:0 0 0 5px;
        }
    }
</style>
<style lang="scss">
    .systemAdminAccount {
        .editDialog {
            .el-radio-group {
                width:100%;
            }
            .el-radio {
                width:100%;
                overflow: hidden;
                text-overflow:ellipsis;
                white-space: nowrap;
                line-height:30px;
            }
        }
    }
</style>
